﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace IN.DX.Common.Converters
{
    public class ByteToImageSourceConverter : IValueConverter
    {
        #region Converter

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //二进制转图片
            if (value != null)
            {
                byte[] byteArray = (byte[])value;
                BitmapImage bmp = null;

                try
                {
                    bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(byteArray);
                    bmp.EndInit();
                }
                catch
                {
                    bmp = null;
                }

                return bmp;

            }
            else
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //图片转二进制

            //if (!value.Equals(null))
            //{
            //    BitmapImage BitmapImage = (BitmapImage)value;
            //    Stream stream = BitmapImage.StreamSource;
            //    byte[] bytes = new byte[stream.Length];
            //    stream.Read(bytes, 0, bytes.Length);
            //    return bytes;  //将流读入到字节数组中
            //}
            //else
            //{
            //    return null;
            //}
            byte[] ByteArray = null;

            //图片转二进制

            if (value != null)
            {
                if (value.GetType().Name == "Byte[]") return value;
                BitmapImage bmp = (BitmapImage)value;
                try
                {
                    Stream stream = bmp.StreamSource;
                    if (stream != null && stream.Length > 0)
                    {
                        stream.Position = 0;
                        using (BinaryReader br = new BinaryReader(stream))
                        {
                            ByteArray = br.ReadBytes((int)stream.Length);
                        }
                    }
                }
                catch
                {
                    return null;
                }

                return ByteArray;
            }

            return null;
        }
        #endregion
    }
}
